<?
/**
 * User: x1t0k
 * Date: 27/02/12
 * Time: 22:16 PM
 */

        class MobileController extends G4T_Controller
        {
            const NEWS_PER_PAGE = 6;
            const ITEMS_PER_PAGE = 6;
            const ADS_PER_PAGE = 6;
            private $_manager;
            private $_user;
            public  $newsId;

            public function init() {
                      parent::init();
                      $this->_manager = new \Managers\Subscribers();
                       $this->_helper->layout()->setLayout('mobile-layout');
                       $this->_user = \Zend_Auth::getInstance()->getStorage()->read();
                       $this->_adManager = new \Managers\Ad();
               }



            public function indexAction()
            {
                   $this->view->title="Главная";
                   if ($this->_getParam('status')){
                         $this->view->status='Вы успешно прошли авторизацию';
                   }
            }

            public function newsAction()
                       {
                              $this->view->title="Новости";

                                                   $page = (int) $this->_getParam('page');

                                                   $newsManagers = new \Managers\News();
                                                   $newsManagers->setLimit(self::NEWS_PER_PAGE);
                                                   $offset = $page > 0 ? ($page - 1) * self::NEWS_PER_PAGE : 0;
                                                   $newsManagers->setOffset($offset);
                                                   $news = $newsManagers->getListWithCommentsCount();
                                                   $this->view->news = $news;
                                                   $total = $newsManagers->getCount(true);
                                                   $arrows=$this->mobilepaginator($page,$total,'','/mobile/news');
                                                                    $this->view->leftrange=$arrows['left'];
                                                                    $this->view->rightrange=$arrows['right'];





                       }

            public function viewnewsAction(){
                $newsManager = new \Managers\News();
                        $article = $newsManager->getByIdWithCommentsAndSimilar($this->_getParam('id'));
                        if (!$article) {
                             $this->_redirect('/mobile/news');
                        }
                        $newsManager->incrementViews($this->_getParam('id'));
                        $this->view->article = $article;
                $this->view->title=$article['title'];
            }
            public function advAction(){
                $this->view->title='Объявления';
                $categoryManager = new \Managers\Category();
                        $categories = $categoryManager->getListWithChildren();
                        $this->view->categories = $categories;
            }
            public function viewadAction(){
                $subcatManager = new \Managers\SubCategory();
                $idOfCategory=$this->_getParam('id');
                $status=0;
                $status=$this->_getParam('status');
                $category = $subcatManager->getById($idOfCategory);
                $this->view->category = $category;
                $this->view->status = $status;
                $name=substr($category['category']['name'],0,-2)." - ".substr($category['name'],0,-1);
                $this->view->title=$name;
                 if (!$category) {
                    $this->_redirect('/mobile/adv');
                }
                $adBuilder = new \Managers\Builder\AdBuilder();
                $adBuilder->setSubCategory($this->_getParam('id'))
                    ->addOrderById();


                        $page = (int) $this->_getParam('page');
                        $offset = $page > 0 ? ($page - 1) * self::ITEMS_PER_PAGE : 0;
                        $total = $adBuilder->getTotal();
                        $this->view->total = $total;

                        $adBuilder->setLimit(self::ITEMS_PER_PAGE, $offset);
                        $ads = $adBuilder->getList();
                        $this->view->ads = $ads;
                        $arrows=$this->mobilepaginator($page,$total,$idOfCategory,'/mobile/viewad/id/');
                                          $this->view->leftrange=$arrows['left'];
                                          $this->view->rightrange=$arrows['right'];




            }
            public  function newscommentAction(){
                $this->view->title='Комментарии';
                $newsId=$this->_getParam('id');
                $this->newsId=$newsId;

                $this->view->error = $this->_getParam('status');
                $this->view->status=$this->_getParam('send');
                $commentsManager = new Managers\Comments();
                $comments = $commentsManager->getAllComments($newsId);

                                   if (empty($comments)) {
                                     $nocomments=1;
                                   }
                                    else{$nocomments=0;}

                  $this->view->comments = $comments;
                  $this->view->nocomments = $nocomments;
                  $this->view->newsid = $newsId;
            }
            public function addcommentAction(){
                if (!is_array($this->_user)){
                $this->_redirect('/mobile/newscomment/id/'.$this->newsId.'/status/1');
                }
                $this->view->title='Добавление комментария';
                $id=$this->_getParam('id');

                $this->view->id = $id;
                $values=array();

                $newsManager = new \Managers\News();
                       if ($newsManager->allowComments($id)) {
                           if ($this->_request->isPost())
                           {
                               $text = $this->_getParam('text');
                               $newsId = $this->_getParam('news');
                               $values['news']=$newsId;
                               $values['text']=$text;
                                   $commentsManager=new Managers\Comments();
                                   $commentsManager->create($this->filterString($values), $this->_user);
                                   $this->_redirect('/mobile/newscomment/id/'.$newsId.'/send/1');

                            }
                       }
            }
            public function contactsAction(){
                $this->view->title='Контакты';
                if ($this->_getParam('send')){
                $this->view->status='Письмо отправлено';
                }
                       if ($this->_request->isPost())
                       {

                           $email=$this->_getParam('emailguest');
                           $subject=$this->_getParam('emailsubject');
                           $message=$this->_getParam('emailmessage');
                           $mailManager= new  \Managers\Mailsend();

                           $mailManager->sendEmail($email,$subject, $message);
                           $this->_redirect("/mobile/contacts/send/1");

                       }

            }
            public function aboutusAction(){
                $this->view->title='О нас';
             }
           public function issuesAction(){
               $this->view->title='Выпуски';
               $pdfManager = new \Managers\PdfFile();
                      $issues = $pdfManager->getList();
                      $this->view->issues = $issues;
           }
            public function archiveAction(){
                $this->view->title='Архив';
                $pdfImageManager = new \Managers\PdfImage();


                    $images = $pdfImageManager->getByFile($this->_getParam('id'));
                    if (!$images){
                        $this->_redirect("/mobile/issues");
                    }
                else{
                    $count_images = count($images);
                    $this->view->images = $images;
                    $this->view->count_images= $count_images;
                }
            }
            public function searchAction(){
               $this->view->title='Поиск';

             }
            public function searchresultAction(){
                $query = $this->_getParam('q');
                      $this->view->query = $query;

                      $searcher = new \Managers\Searchers\News();

                      $page = (int) $this->_getParam('page');
                      $offset = $page > 0 ? ($page - 1) * self::NEWS_PER_PAGE : 0;
                      $searcher->setLimit($offset, self::NEWS_PER_PAGE);
                      $searcher->addQuery($query);

                      $manager = new \Managers\News();
                      try {
                          $resultManager = new \Managers\Result\Base($searcher, $manager);
                          $resultManager->setDecorator(new \Managers\Decorators\NewsSearch($query));
                          $result = $resultManager->getResult();
                          $this->view->news = $result;
                          $total = $resultManager->getTotalResults();
                          $this->view->total = $total;
                          $arrows=$this->mobilepaginator($page,$total,$query,'/mobile/searchresult/q/');
                          $this->view->leftrange=$arrows['left'];
                          $this->view->rightrange=$arrows['right'];
                           }
                      catch (LogicException $e) {
                          $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                      } catch (Exception $e) {
                          $this->handleException($e);
                      }


            }
            public function subscribeAction(){
                           $this->view->title='Подписка';
//                if ($this->_request->isPost()) {

                if ($this->_request->isPost()) {


                               $values =array();
                               $values['email']=$this->_getParam('email');

                               try {
                                   $entity = $this->_manager->create($values);
                                   $mail = new \Managers\Mailer\Subscribe($entity);
                                   $mail->send();
                                   $this->_saveCookie();
                                   $this->view->message = "Спасибо за подписку.";

                               }
                               catch (LogicException $e) {
                                   $this->view->message = $e->getMessage();
                               }
                               catch (Exception $e) {
                                   $this->view->message = 'Что-то пошло не так.';
                                   $this->handleException($e);
                               }

                       }
             }
            private function _saveCookie()
              {
                  setcookie('subscribe', sha1(mt_rand()), time() + 365 * 24 * 3600, '/');
              }
           private  function  mobilepaginator($page,$total,$query,$url){
               if (!isset($page)){ $page=0; }
                          $left=$page-1;

                          if ($left<=0)
                          {
                              $leftrange=$url.$query;
                          }
                          else {$leftrange=$url.$query."/page/".$left;}

                          $right=$page+1;
                           if ($right==1){$right++;}
                          if (($page)*self::NEWS_PER_PAGE>=$total)
                          {
                              $rightrange='#';
                          }
                          else { $rightrange=$url.$query."/page/".$right;}
               $arrows=array();
               $arrows['left']=$leftrange;
               $arrows['right']=$rightrange;
               return $arrows;






           }
            public function tagAction()
             {
                 $this->view->title='Поиск по тегам';
                 $tagsManager = new \Managers\Tags();
                 $tag = $tagsManager->getByIdWithNews($this->_getParam('id'));


                 if (!$tag) {
                     $this->view->message='Тег не найден';

                 }
                 else{
                 $this->view->searchtag = $tag['name'];
                 $this->view->news = $tag['news'];
                 }

             }
            public function issueAction()
               {
                   $this->view->title='Поиск по номеру газеты';
                   $page = (int)$this->_getParam('page');
                   $issueManager = new \Managers\Issue();
                   $id=$this->_getParam('id');
                   $issue = $issueManager->getById($id);
                   $this->view->issue = $issue;
                   if (!$issue) {
                       $this->view->message="Номер газеты не найден.";
                            }
                   else{
                   $newsBuilder = new \Managers\Builder\NewsBuilder();
                   $newsBuilder->setIssue($issue['id']);
                   $total = $newsBuilder->getTotal();
                   $this->view->total = $total;
                   $offset = $this->getOffet($page);
                   $newsBuilder->setLimit(self::NEWS_PER_PAGE, $offset);
                   $news = $newsBuilder->getList();
                   $this->view->news = $news;
                   $arrows=$this->mobilepaginator($page,$total,$id,'/mobile/issue/id/');
                    $this->view->leftrange=$arrows['left'];
                    $this->view->rightrange=$arrows['right'];

                   }
                   $this->renderScript('/mobile/news.phtml');
               }
            private function getOffet($page)
               {
                   return $page > 0 ? ($page - 1) * self::NEWS_PER_PAGE : 0;
               }
            public function advlistAction(){
                 $this->view->title='Добавление объявления';
                 $categoryManager = new \Managers\Category();
                 $categories = $categoryManager->getList();

                 $this->view->categories = $categories;
            }
            public function addadvAction(){

                $categoryId = $this->_getParam('id');
                $categoryManager = new \Managers\Category();
                $category = $categoryManager->getById($categoryId);
                $this->view->category = $category;
                if (!$category) {
                            $this->_redirect('/mobile/advlist');
                }
                else{
                    $nameOfCategory=$category['name'];
                    $this->view->title= "Вы добавляете объявление для рубрики \"$nameOfCategory\"";
                    $subcatManager = new \Managers\SubCategory();
                    $subcats = $subcatManager->getByCategory($categoryId);
                    $this->view->list=$subcats;
                    $this->view->user=$this->_user;
                }
                        if ($this->_request->isPost()) {
                                $adManager = new \Managers\Ad();
                                $values=$this->filterString($this->_getParam('form'));
                                $ad = $adManager->create($values, $this->_user);
                                $this->_redirect("/mobile/viewad/id/".$ad->getSubCat()->getId()."/status/1");
                            }
            }
            private function deletePoint($category){
                return substr(preg_replace('/\./','',$category),0,-1);
            }
            private function filterString(array $values){
                $tagsFilter= new Zend_Filter_StripTags();
                $trimFilter = new \Zend_Filter_StringTrim();

                foreach ($values as $key=>$value)
                {
                    $values[$key]=$trimFilter->filter($tagsFilter->filter($value));

                }
                return $values;
            }
            public function authAction(){
                $this->view->title="Регистрация";
                $status=$this->_getParam('status');
                if ($status){
                    $this->view->status='Пройдите авторизацию или зарегистрируйтесь.';
                }

            }
            public function registerAction(){
                           $this->view->title="Регистрация";
                if ($this->_user) {
                                      $this->_redirect('/mobile');
                                  }

                                  $form = new App_Form_User_Register();

                                  if ($this->_request->isPost()) {
                                      $params = $this->_request->getParams();
                                      if ($form->isValid($params)) {
                                          $values = $form->getValues();
                                          $usersManager = new \Managers\Users();
                                          $usersManager->create($params);
                                          $usersManager->auth($values['email'], $values['password']);
                                          $this->_redirect('/mobile');
                                      }
                                  }

                                  $this->view->form = $form;
                       }
            public function loginAction(){

                if ($this->_user)
                {
                            $this->_redirect('/mobile');
                }
                        if ($this->_request->isPost()) {

                                $values = $this->_getParam('form');
                                $usersManager = new \Managers\Users();
                                try {
                                    $result = $usersManager->auth($values['email'], $values['password']);
                                    if ($result) {
                                        if ($values['remember']) {
                                            $this->rememberMe($result);
                                        }
                                        $this->_redirect('/mobile/status/1');
                                    } else {

                                        $this->view->error='Неверный логин или пароль';
                                    }
                                } catch (LogicException $e) {
                                    $this->view->error=$e->getMessage();
                                }
                            }




                           $this->view->title="Авторизация";
                       }
            private function rememberMe($user)
               {
                   $userManager = new \Managers\Users();
                   $cookieData = $userManager->getCookieData($user);
                   setcookie('user', $cookieData, time() + 365 * 24 * 3600, '/');
               }
            public function homeAction(){
                $this->view->title="Профайл";
                 if($this->_user){
                     $status=$this->_getParam('status');
                                     if ($status){
                                         $this->view->status='Объявление удалено.';
                                     }
                        $this->view->user=$this->_user;

                             $page = intval($this->_getParam('page'));

                             $adBuilder = new \Managers\Builder\AdBuilder();
                             $adBuilder->setUser($this->_user['id']);

                             $total = $adBuilder->getTotal();
                             $this->view->total = $total;
                             $this->displayPaginantor($total, $page, self::ADS_PER_PAGE);

                             $offset = $this->_getOffset($page, self::ADS_PER_PAGE);
                             $adBuilder->setLimit(self::ADS_PER_PAGE, $offset);
                             $ads = $adBuilder->getList();

                             $this->view->ads = $ads;
                             $arrows=$this->mobilepaginator($page,$total,'','/mobile/home');
                             $this->view->leftrange=$arrows['left'];
                              $this->view->rightrange=$arrows['right'];
                 }
                else {
                    $this->_redirect('/mobile/auth/status/1');
                }
            }
            public function deleteAction()
                {
                    $result = $this->_adManager->delete($this->_getParam('id'), $this->_user['id']);
                    $this->_redirect('/mobile/home/status/1');
                }
            public function logoutAction()
            {
                \Zend_Auth::getInstance()->clearIdentity();
                setcookie('user', '', time(), '/');
                $this->_redirect('/mobile');
            }

        }

